package com.leidy.study.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
import org.springframework.security.oauth2.provider.code.InMemoryAuthorizationCodeServices;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

import javax.annotation.Resource;

/**
 * @author leidy
 * @since 2025/7/28 上午8:48
 */
@Configuration
public class MyAuthorizationConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthorizationCodeServices authorizationCodeServices;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private TokenStore tokenStore;

    @Autowired
    private ClientDetailsService clientDetailsService;

    @Resource(name = "myAccessTokenConverter")
    private JwtAccessTokenConverter jwtAccessTokenConverter;


    public AuthorizationServerTokenServices tokenService() {
        DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
        // 令牌存储方式
        defaultTokenServices.setTokenStore(tokenStore);
        // 令牌使用JWT
        defaultTokenServices.setTokenEnhancer(jwtAccessTokenConverter);
        // 客户端详情服务
        defaultTokenServices.setClientDetailsService(clientDetailsService);
        // 是否支持刷新令牌
        defaultTokenServices.setSupportRefreshToken(true);
        // 令牌默认有效期 12 小时 = 43200秒
        defaultTokenServices.setAccessTokenValiditySeconds(60 * 60 * 12);
        // 刷新令牌默认有效期 7 天 = 604800秒
        defaultTokenServices.setRefreshTokenValiditySeconds(60 * 60 * 24 * 7);
        return defaultTokenServices;
    }

    /**
     * 授权码模式暂时用内存方式存取
     */
    @Bean
    public AuthorizationCodeServices authorizationCodeServices() {
        return new InMemoryAuthorizationCodeServices();
    }


    /**
     * 配置客户端详情服务
     * 简化模式：浏览器测试访问 <a href="http://localhost:53020/uaa/oauth/authorize?client_id=c1&response_type=token&scope=all&redirect_uri=http://www.baidu.com">...</a>
     * 授权码模式：浏览器测试访问 <a href="http://localhost:53020/uaa/oauth/authorize?client_id=c1&response_type=code&scope=all&redirect_uri=http://www.baidu.com">...</a>
     * 1、比如登录成功后授权跳转的地址为 <a href="https://www.baidu.com/?code=IXJGy9">...</a>
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        // 内存配置的方式配置用户信息
        clients.inMemory() // 内存方式
                .withClient("c1") // client_id
                .secret(new BCryptPasswordEncoder().encode("secret")) // 客户端秘钥
                .resourceIds("salary") // 客户端拥有的资源列表
                .authorizedGrantTypes("authorization_code",
                        "password", "client_credentials", "implicit", "refresh_token") // 授权类型
                .scopes("all") // 允许的授权范围
                .autoApprove(false) // 跳转到授权页面
                .redirectUris("http://www.baidu.com"); // 回调地址
    }

    /**
     * 配置令牌端点的安全约束
     * 即：令牌不是谁都来申请的
     * 也不是谁都能来验证的
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security.tokenKeyAccess("permitAll()")
                .checkTokenAccess("permitAll()")
                .allowFormAuthenticationForClients();
    }

    /**
     * 用来配置令牌TOKEN的访问端点和令牌服务
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
                .pathMapping("/oauth/confirm_access", "/customer/confirm_access") // 定制授权确认页面路径
                .authenticationManager(authenticationManager) // 认证管理器
                .userDetailsService(userDetailsService) // 密码模式的用户信息管理
                .authorizationCodeServices(authorizationCodeServices) // 授权码服务
                .tokenServices(tokenService()) // 令牌管理服务
                .allowedTokenEndpointRequestMethods(HttpMethod.POST); // 允许的令牌端点请求方法
    }
}
